<template>
  <div class="register-form">
    注册账号
    <el-form
      ref="registerForm"
      :model="formData"
      :rules="rules"
      @submit.prevent="handleSubmit"
      label-width="80px"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="formData.username"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">注册</el-button>
        <el-button @click="handleBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';

const formData = ref({
  username: '',
  password: '',
  name: ''
});

const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
};

const router = useRouter();

const handleSubmit = async () => {
  try {
    const res = await axios.post('/register', formData.value);
    ElMessage({
      message: '注册成功',
      type: 'success'
    });
    console.log(res);
  } catch (err: any) {
    ElMessage({
      message: `${err.response.data.msg}`,
      type: 'warning'
    });
  }
};

const handleBack = () => {
  // 返回按钮点击事件处理逻辑，返回到上一页
  router.push('/login');
};
</script>

<style scoped>
.register-form {
  width: 300px;
  margin: 0 auto;
}
</style>
